<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : AdminUserToken.php
 * Created on : 2020-7-25 10:50:38
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */

namespace app\admin\model;

use think\Model;
use app\admin\model\AdminUser;

/**
 * 
 * Class AdminUserToken
 * Tiger <1192851302@qq.com> 2020-7-25 10:50:38
 */
class AdminUserToken extends Model {

    protected $name = 'admin_user_token';

    /**
     * 创建token并且保存
     * @author Tiger <1192851302@qq.com>
     * @param AdminUser $user
     * @param $type
     * @return UserToken
     */
    public static function createToken(AdminUser $user, $type): self {
        $tokenInfo = $user->getToken($type);
        try {
            $return = self::create(['uid' => $user->id, 'token' => $tokenInfo['token'], 'expires_time' => date('Y-m-d H:i:s', $tokenInfo['params']['exp'])]);
        } catch (\Exception $exc) {
            exception($exc->getMessage());
        }
        return $return;
    }

    /**
     * 删除一天前的过期token
     * @author Tiger <1192851302@qq.com>
     * @return bool
     * @throws \Exception
     */
    public static function delToken() {
        return self::where('expires_time', '<=', date('Y-m-d H:i:s', strtotime('-1 day')))->delete();
    }

    /**
     * 
     * @author Tiger <1192851302@qq.com>
     * @param type $token
     * @return type
     */
    public static function parseToken($token) {
        if (empty($token)) {
            exception('参数错误,请重新登录', 410000);
        }
        try {
            list($admin, $type) = AdminUser::parseToken($token);
        } catch (\Throwable $e) {
            exception($e->getMessage() ?: '登录已过期,请重新登录', 410001);
        }

        if ($admin['state'] == 0) {
            exception('已被锁定', 410003);
        }

        return compact('admin', 'type');
    }

}
